import Router from 'koa-router';
import { Character } from '../models/Character';
import { ResponseUtil } from '../utils/response';
import { validatePagination } from '../middleware/validation';

const router = new Router();
const characterModel = new Character();

/**
 * 获取角色列表
 * GET /api/characters
 */
router.get('/', validatePagination, async (ctx) => {
  try {
    const page = parseInt(ctx.query.page as string) || 1;
    const limit = parseInt(ctx.query.limit as string) || 10;
    const isActive = ctx.query.is_active === 'true' ? true : ctx.query.is_active === 'false' ? false : undefined;

    const result = await characterModel.getCharactersWithPagination({ page, limit }, isActive !== undefined ? { is_active: isActive } : {});

    ctx.body = ResponseUtil.success(ctx, result, '获取角色列表成功');
  } catch (error) {
    throw error;
  }
});

/**
 * 根据ID获取角色详情
 * GET /api/characters/:id
 */
router.get('/:id', async (ctx) => {
  try {
    const id = parseInt(ctx.params.id);

    if (isNaN(id)) {
      ctx.status = 400;
      ctx.body = ResponseUtil.error(ctx, "无效的角色ID", "BAD_REQUEST", 400);
      return;
    }

    const character = await characterModel.findById(id);

    if (!character) {
      ctx.status = 404;
      ctx.body = ResponseUtil.error(ctx, "角色不存在", "NOT_FOUND", 404);
      return;
    }

    ctx.body = ResponseUtil.success(ctx, character, '获取角色详情成功');
  } catch (error) {
    throw error;
  }
});



export default router;